import React from "react";
import { connect } from "dva";
import { Form, Input, Select, Modal, Spin, Upload, Button, Icon } from "antd"; // Switch
import { equals } from "@cbd/utils";
import { openNotificationWithIcon } from "../../../../utils/comm";

const { Option } = Select;
const { TextArea } = Input;

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const formItemLayout2 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 10 },
};

@Form.create()
@connect(({ loading }) => ({
  loading: loading.effects["FlowConfigure/getModelDetail"],
}))


class ImportFlow extends React.Component {
  state = {
    bussiesArr: [],
    fileList: [],
    checkModel: false,
  };

  openNotificationWithIcon = openNotificationWithIcon.bind(this);

  componentDidMount() {
    const { appList, appBusinessObj } = this.props;

    this.setFormValue();

    if (appList.length > 0) {
      const appId = appList[0].id;
      const bussiesArr = appBusinessObj[appId] || [];
      this.setState({ bussiesArr });
    }
  }

  componentDidUpdate(preProps) {
    const { data, route, appBusinessObj } = this.props;
    if (!equals(data, preProps.data)) {
      this.setFormValue();
      this.changeBuss();
    }
    if (!equals(route, preProps.route)) {
      if (route.length > 1) {
        const appId = route[1];
        const bussiesArr = appBusinessObj[appId] || [];
        this.setBussiesArr(bussiesArr);
      }
    }
  }

  setBussiesArr = (arr) => {
    this.setState({ bussiesArr: arr });
  };

  setFormValue = () => {
    const { data, form } = this.props;
    if (data) {
      const {
        appId,
        busiId,
        modelId,
        modelKey = "",
        modelName: name,
        description,
      } = data;
      this.modelId = modelId;
      form.setFieldsValue({
        appId,
        busiId,
        key: `copy${modelKey}`,
        name,
        description,
      });
    }
  };

  changeBuss = () => {
    const { data = {}, appList, appBusinessObj } = this.props;
    const { appId } = data || {};
    if (data.appId && appList.length > 0) {
      const bussiesArr = appBusinessObj[appId] || [];
      this.setState({ bussiesArr });
    }
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const params = new FormData();
      params.append('appId', values.appId);
      params.append('busiId',values.busiId);
      params.append('key', values.key);
      params.append('name',values.name);
      params.append('description',values.description);
      params.append('file',values.upload.file);
      dispatch({
        type: "FlowConfigure/importFlow",
        payload: params,
      }).then(({ errMsg, success }) => {
        if (success === true) {
          this.handleCancel();
          this.openNotificationWithIcon("success", "", errMsg || '导入成功');
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    });
  };

  handleCancel = () => {
    const { handleImportVisible, form } = this.props;
    form.resetFields();
    this.setState({fileList: []})
    handleImportVisible(false);
  };

  handleAppIdChange = (value) => {
    const { appBusinessObj, form } = this.props;
    const bussiesArr = appBusinessObj[value] || [];
    const busiId = bussiesArr.length > 0 ? bussiesArr[0].id : "";
    form.setFieldsValue({ busiId });
    this.setState({ bussiesArr });
  };

  handleUploadChange = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    this.setState({ fileList });
  }

  checkModelExist = (modelName, modelKey) => {
    const { dispatch } = this.props;
    dispatch({
      type: "FlowConfigure/checkModelExist",
      payload: {modelName, modelKey},
    }).then((res) => {
      if (res.success === true) {
        this.setState({checkModel: res.datas})
      }
    });
  }

  confirmOk = () => {
    const { form } = this.props;
    form.validateFields((err) => {
      if (err) {
        return;
      }
      // eslint-disable-next-line react/destructuring-assignment
      const content = this.state.checkModel? `流程模板已存在，点击确认会覆盖原来模板` : `确认导入此项吗?`
      const _this = this
      Modal.confirm({
        okText: '确认',
        cancelText: '取消',
        content,
        onOk () {
          _this.handleOk();
        },
        onCancel() {},
      });
    })
  }

  render() {
    const {
      form,
      visible,
      confirmLoading,
      appList,
      loading,
      route,
    } = this.props;
    const { fileList } = this.state;
    const { getFieldDecorator } = form; // getFieldValue
    return (
      <Modal
        title="导入流程模型"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width="642px"
        centered
        confirmLoading={confirmLoading}
        destroyOnClose
        footer={[
          <Button key="back" onClick={this.handleCancel}> 取消 </Button>,
          <Button key="submit" type="primary" loading={loading} onClick={this.confirmOk}>
            确认
          </Button>,
          ]}
      >
        <Spin spinning={!!loading}>
          <Form>
            <Form.Item label="流程模型文件" {...formItemLayout1}>
              {getFieldDecorator('upload', {
                rules: [
                  { required: true, message: "请上传流程模型文件" },
                ],
          })(
            <Upload
              name='file'
              accept=".json"
              onChange={this.handleUploadChange}
              fileList={fileList}
              beforeUpload={
                file => {
                  const reader = new FileReader();
                  // eslint-disable-next-line no-shadow
                  const { form } = this.props;
                  reader.readAsText(file)
                  // reader.readAsBinaryString(file);// 读取文件的原始二进制数据
                  reader.onload = ev=>{
                    // eslint-disable-next-line prefer-destructuring
                    const result = ev.target.result;
                    // console.log(result)
                    if (result){
                      const re = JSON.parse(result);
                      form.setFieldsValue({name: re.name});
                      form.setFieldsValue({key: re.key});
                      if (appList && appList.map(i=>i.id).includes(re.appId)){
                        form.setFieldsValue({appId: re.appId});
                        this.handleAppIdChange(re.appId)
                      }
                      // eslint-disable-next-line react/destructuring-assignment
                      if (this.state.bussiesArr && this.state.bussiesArr.map(i=>i.id).includes(re.busiId)){
                        form.setFieldsValue({busiId: re.busiId});
                      }
                      this.checkModelExist(re.name, re.key);
                    }
                  }
                  this.setState(state => ({
                    fileList: [...state.fileList, file],
                  }));
                  return false;
                }
              }
            >
              <Button>
                <Icon type="upload" />
                上传BPMN2.0文件
              </Button>
            </Upload>,
          )}
            </Form.Item>
            <Form.Item label="流程模型名称" {...formItemLayout1}>
              {getFieldDecorator("name", {
                initialValue: "",
                rules: [
                  { required: true, message: "请输入流程名称" },
                  { max: 20, message: "流程名称长度不能超过20" },
                ],
              })(<Input maxLength={20} placeholder="请输入流程名称" />)}
            </Form.Item>
            <Form.Item label="流程模型编码" {...formItemLayout1}>
              {getFieldDecorator("key", {
                initialValue: "",
                rules: [
                  { required: true, message: "请输入流程编码" },
                  { max: 20, message: "编码长度不能超过20" },
                  {
                    pattern: /^[a-zA-Z_][a-zA-Z_0-9-]*$/,
                    message:
                      "支持字母、数字、下划线、中划线，须以字母或者下划线开头",
                  },
                ],
              })(<Input maxLength={20} placeholder="请输入流程编码" />)}
            </Form.Item>

            <Form.Item label="所属应用" {...formItemLayout2}>
              {getFieldDecorator("appId", {
                initialValue: route[1] || undefined,
                rules: [{ required: true, message: "请选择所属应用" }],
              })(
                <Select
                  placeholder="请选择所属应用"
                  onChange={this.handleAppIdChange}
                >
                  {appList.map((item) => (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="所属业务" {...formItemLayout2}>
              {getFieldDecorator("busiId", {
                initialValue: route[2] || undefined,
                rules: [{ required: true, message: "请选择所属业务" }],
              })(
                <Select placeholder="请选择所属业务">
                  {/* eslint-disable-next-line react/destructuring-assignment */}
                  {this.state.bussiesArr.map((item) => (
                    <Option key={`${item.id}${item.name}`} value={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
            {/* <Form.Item
                  label="是否公开流程"
                  {...formItemLayout1}
                >
                  {getFieldDecorator('isOpen', {
                    initialValue: false,
                    valuePropName: 'checked',
                    rules: [{ required: true }],
                  })(
                    <Switch style={{ width: 70 }} checkedChildren="公开" unCheckedChildren="不公开" />
                  )}
                  <span style={{ paddingLeft: 10, color: '#bfbfbf' }}>
                    {getFieldValue("isOpen") ? '公开流程后其他租户将也能看到此流程' : '不公开流程后其他租户将看不到此流程'}
                  </span>
                </Form.Item> */}
            <Form.Item label="流程说明" {...formItemLayout1}>
              {getFieldDecorator("description", {
                initialValue: "",
                rules: [{ max: 100, message: "流程说明长度不能超过100" }],
              })(<TextArea placeholder="请输入流程说明" rows={4} />)}
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    );
  }
}
export default ImportFlow;
